from sqlalchemy.sql.schema import Column
from sqlalchemy.sql.sqltypes import Boolean, Integer, String, Text, DateTime
from sqlalchemy.sql.functions import func
from sqlalchemy.orm import relationship

from app.core.database import Base


class Permission(Base):
    """权限模型 - RBAC中的Permission"""
    __tablename__ = "permissions"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), unique=True, index=True, nullable=False)
    display_name = Column(String(200), nullable=False)
    description = Column(Text)
    
    # 权限分类
    category = Column(String(50), index=True, nullable=False)  # 如: user, role, system, etc.
    action = Column(String(50), nullable=False)  # 如: create, read, update, delete
    resource = Column(String(100), nullable=False)  # 如: user, role, permission
    
    # 状态字段
    is_active = Column(Boolean, default=True, nullable=False)
    is_system = Column(Boolean, default=False, nullable=False)  # 系统内置权限
    
    # 审计字段
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关联关系
    role_permissions = relationship("RolePermission", back_populates="permission", cascade="all, delete-orphan")
    roles = relationship("Role", secondary="role_permissions", back_populates="permissions", overlaps="role_permissions")
    
    def __repr__(self):
        return f"<Permission(id={self.id}, name='{self.name}', category='{self.category}')>"
    
    @classmethod
    def create_permission_name(cls, action: str, resource: str) -> str:
        """创建权限名称的标准格式"""
        return f"{action}_{resource}"
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            "id": self.id,
            "name": self.name,
            "display_name": self.display_name,
            "description": self.description,
            "category": self.category,
            "action": self.action,
            "resource": self.resource,
            "is_active": self.is_active,
            "is_system": self.is_system,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None
        }